<template>
  <div class="chart-container" ref="chartRef"></div>
</template>

<script lang="ts" setup>
// pnpm add lodash-es
// pnpm add @types/lodash-es -D
import { merge } from "lodash-es";
import { ref, watch, onMounted, PropType } from "vue";
import echarts from "../../utils/echarts";
import type { ECOption } from "../../utils/echarts";
import defaultOption from "./defaultOption";

defineOptions({
  name: "Chart",
});

const props = defineProps({
  option: {
    type: Object as PropType<ECOption>,
    required: true,
  },
});

// 将默认配置和传入的配置合并，生成新配置
// const option = Object.assign(defaultOption, props.option); // 不行（原因：只进行浅合并）

// 深度合并
// 不行(原因：生成option都和defaultOption指向同一个地址值，导致所有图表只渲染最后一个)
// const option = merge(defaultOption, props.option);

const chartRef = ref();

let myEcharts: echarts.ECharts;

const render = () => {
  const option = merge({}, defaultOption, props.option);
  myEcharts.setOption(option);
};

onMounted(() => {
  myEcharts = echarts.init(chartRef.value);
  render();
});

watch(
  () => props.option,
  () => {
    if (!myEcharts) return;
    render();
  },
  { deep: true }
);
</script>

<style scoped lang="scss">
.chart-container {
  width: 100%;
  height: 100%;
}
</style>
